<template>
	<view class="common-bg" :class="{ 'popup-open': isPopupOpen }">
		<view class="pad-20">
			<uni-nav-bar :statusBar="true" :border="false" left-icon="back" right-icon="gear"
				background-color="transparent" @clickLeft="clickLeft" @clickRight="clickRight">
				<view class="text-center w-100">
					<view class="device-name-title">
						{{ deviceDetail.device_name || '设备名称' }}
					</view>
					<view class="device-status-info">
						<text class="status-dot" :class="{ 'online': deviceStore.isDeviceOnline(deviceSn), 'offline': !deviceStore.isDeviceOnline(deviceSn) }">●</text>
						<text class="status-text">{{ deviceStore.isDeviceOnline(deviceSn) ? '在线' : '离线' }}</text>
						<text class="status-divider playback-status" :class="'status-' + currentPlaybackStatus">•</text>
						<text class="status-text">{{ getPlaybackStatusText() }}</text>
					</view>
				</view>
			</uni-nav-bar>
			<view class="img-box flex-center-center shadow">
				<image class="img" v-if="currentPattern" :src="currentPattern.preview_image" mode=""></image>
			</view>
			<view class="font-24 col-000-8 font-500 m-t-24">
				{{ currentPattern.pattern_name }}
			</view>
			<view class="bottom-control">
				<!-- 归零和扫图状态下隐藏进度条 -->
				<view class="progress" v-if="currentPlaybackStatus !== 'homing' && currentPlaybackStatus !== 'sweeping'">
					<slider class="audio-slider" activeColor="rgba(0,0,0,0.8)" block-size="12"
						backgroundColor="rgba(0,0,0,0.08)" :value="playDetailInfo.current_value"
						:max="playDetailInfo.duration_value" :disabled="true"></slider>

				</view>
				<view class="flex flex-center flex-between" v-if="currentPlaybackStatus !== 'homing' && currentPlaybackStatus !== 'sweeping'">
					<view class="audio-number">{{ playDetailInfo.current }}</view>
					<view class="audio-number">{{ playDetailInfo.duration }}</view>
				</view>
				<view class="flex-center-center play-btn-box">
					<view class="play-img" @click="handleChangePlay(-1)" :class="{ 'disabled': isControlDisabled }">
						<image class="w-100" src="/static/images/left.png" mode="widthFix"></image>
					</view>
					<view class="play-img-btn" @click="playMusic" :class="{ 'disabled': isControlDisabled }">
						<image class="w-100" :src="currentPattern.status === 1 ? '/static/images/paused.png' : '/static/images/next.png'"
							mode="widthFix"></image>
					</view>
					<view class="play-img" @click="handleChangePlay(1)" :class="{ 'disabled': isControlDisabled }">
						<image class="w-100" src="/static/images/next.png" mode="widthFix"></image>
					</view>
				</view>
				<view class="btns-box">
					<view class="control-img play-type" @click="togglePlaybackMode" :class="{ 'disabled': isControlDisabled }">
						<image class="w-100" :src="playbackModeIcon" mode="widthFix"></image>
					</view>
					<view class="control-img play-type" @click="lightControl()">
						<image class="w-100" src="/static/images/light.png" mode="widthFix"></image>
					</view>
					<view class="control-img play-type" @click="playControl()">
						<image class="w-100" src="/static/images/control.png" mode="widthFix"></image>
					</view>
					<view class="control-img play-type" @click="playList()">
						<image class="w-100" src="/static/images/list.png" mode="widthFix"></image>
					</view>
				</view>
				<view class="">
					<MyCollectionSet />
				</view>
			</view>
		</view>
		<!-- 灯光控制 -->
		<comLightControl ref="ref_light_control" @close="onPopupClose" />
		<!-- 播放控制 -->
		<comPlayControl ref="ref_play_control" @close="onPopupClose" />
	</view>
</template>
<script>
import comLightControl from '@/components/control-light/index.vue'
import comPlayControl from '@/components/control-play/index.vue'
import MyCollectionSet from '@/components/my-collection-set/index.vue'
import deviceApi from '@/api/device.js';
import patternApi from '@/api/pattern.js';
import playlistApi from '@/api/playlist.js';
import mqttApi from '@/api/my-mqtt.js';
import deviceStatusMixin from '@/mixins/deviceStatusMixin.js';
import deviceStore from '@/store/deviceStore.js';
import {
	mapState
} from "vuex";
export default {
	mixins: [deviceStatusMixin],
	data() {
		return {
			deviceSn: '', // 设备序列号
			status: 1,
			deviceDetail: {},
			showDebug: true, // 显示调试信息
			currentPlaybackStatus: '', // 当前播放状态: playing/paused/homing/sweeping/stopped
			playDetailInfo: {
				current: "00:00",
				duration: "00:00",
				current_value: 0,
				duration_value: 100,
			},
			//当前播放图案信息
			currentPattern: {
				pattern_id: '',
				pattern_name: '',
				preview_image: '',
				progress: 0,
				status: 0, //播放状态: 0=停止, 1=播放, 2=暂停
				duration: 0,
				elapsed_time: 0,
				remaining_time: 0
			},
			// 播放状态
			paused: true,
			// 播放模式: 'sequential'(顺序), 'random'(随机), 'single_loop'(单曲循环)
			playbackMode: 'sequential',
			// 播放进度定时器
			progressTimer: null,
			// 本地播放进度（秒）
			localPlayedDuration: 0,
			// 弹窗打开状态(用于防止iOS滚动穿透)
			isPopupOpen: false
		}
	},
	components: {
		comLightControl,
		comPlayControl,
		MyCollectionSet
	},
	computed: {
		// 将deviceStore暴露给模板使用
		deviceStore() {
			return deviceStore;
		},
		// 获取播放模式图标
		playbackModeIcon() {
			switch (this.playbackMode) {
				case 'random':
					return '/static/images/suij.png'; // 随机
				case 'sequential':
					return '/static/images/xunh.png'; // 顺序
				case 'single_loop':
					return '/static/images/xunh.png'; // 单一循环(暂时用顺序图标)
				default:
					return '/static/images/xunh.png';
			}
		},
		// 判断控制按钮是否应该禁用
		isControlDisabled() {
			// 设备离线时禁用
			if (!deviceStore.isDeviceOnline(this.deviceSn)) {
				return true;
			}
			// 归零中或扫图中时禁用
			if (this.currentPlaybackStatus === 'homing' || this.currentPlaybackStatus === 'sweeping') {
				return true;
			}
			return false;
		},
		// 获取禁用原因提示文本
		disabledReasonText() {
			if (!deviceStore.isDeviceOnline(this.deviceSn)) {
				return this.$t('detail.deviceOffline');
			}
			if (this.currentPlaybackStatus === 'homing') {
				return this.$t('detail.deviceHomingWait');
			}
			if (this.currentPlaybackStatus === 'sweeping') {
				return this.$t('detail.deviceSweepingWait');
			}
			return this.$t('detail.cannotControlNow');
		}
		// ...mapState({
		// 	playInfo: (state) => state.playInfo,
		// 	paused: (state) => state.paused,
		// }),
	},
	onLoad(option) {
		// 直接接收设备SN参数
		const sn = option?.sn || '';
		this.deviceSn = sn;
		if (!sn) {
			uni.showToast({
				title: this.$t('list.device_not_exist'),
				icon: 'none'
			})
			return
		}
		
		
		// 延迟执行，确保组件完全初始化
		this.$nextTick(async () => {
			// 0. 先获取设备详情信息
			console.log('[DETAIL] 步骤0: 获取设备详情');
			await this.getDeviceDetail();
			
			// 从缓存中获取设备状态，如果有数据则直接使用
			await this.updateFromMqttCache();
			
			// 1. 先推送播放列表到设备
			console.log('[DETAIL] 步骤1: 推送播放列表到设备');
			const syncResult = await playlistApi.syncPlaylistToDevice({ deviceSn: this.deviceSn })
			if (syncResult.errCode === 0) {
				console.log(`[DETAIL] 播放列表推送成功:`, syncResult.data)
			} else {
				console.warn(`[DETAIL] 播放列表推送失败:`, syncResult.errMsg)
			}
			
			// 2. 然后请求设备当前状态
			console.log('[DETAIL] 步骤2: 请求设备当前状态');
			await mqttApi.requestDeviceStatus(this.deviceSn)
			
			// 初始化播放详情
			this.updatePlayDetailInfo();
		});
	},

	mounted() {
		// mounted 钩子保持为空或用于其他初始化
	},
	
	onUnload() {
		// 页面卸载时清除定时器
		this.stopProgressTimer();
	},
	
	onHide() {
		// 页面隐藏时清除定时器
		this.stopProgressTimer();
	},
	
	onShow() {
		// 页面显示时，如果正在播放则重启定时器
		if (!this.paused && this.currentPattern.status === 1) {
			this.startProgressTimer();
		}
	},

	methods: {
		// 获取设备详情
		async getDeviceDetail() {
			try {
				console.log('[DETAIL] 获取设备详情, SN:', this.deviceSn);
				const res = await deviceApi.getDeviceDetail({ sn: this.deviceSn });
				
				if (res.errCode === 0 && res.data) {
					this.deviceDetail = res.data;
					console.log('[DETAIL] 设备详情获取成功:', this.deviceDetail);
				} else {
					console.warn('[DETAIL] 设备详情获取失败:', res.errMsg);
					// 即使失败也初始化基本结构，避免undefined错误
					this.deviceDetail = {
						device_name: '设备名称',
						sn: this.deviceSn,
						device_status: 0
					};
				}
			} catch (error) {
				console.error('[DETAIL] 获取设备详情异常:', error);
				// 异常时也初始化基本结构
				this.deviceDetail = {
					device_name: '设备名称',
					sn: this.deviceSn,
					device_status: 0
				};
			}
		},
		
		// 启动播放进度定时器
		startProgressTimer() {
			// 先清除之前的定时器
			this.stopProgressTimer();
			
			console.log('[DETAIL] 启动播放进度定时器');
			
			// 每秒更新一次播放进度
			this.progressTimer = setInterval(() => {
				if (!this.paused && this.currentPattern.status === 1) {
					// 增加本地播放进度
					this.localPlayedDuration += 1;
					
					// 检查是否超过总时长
					if (this.localPlayedDuration >= this.currentPattern.duration) {
						this.localPlayedDuration = this.currentPattern.duration;
						// 可以选择停止定时器，等待设备切换到下一首
						// this.stopProgressTimer();
					}
					
					// 更新显示
					this.updatePlayDetailInfo();
				}
			}, 1000);
		},
		
		// 停止播放进度定时器
		stopProgressTimer() {
			if (this.progressTimer) {
				console.log('[DETAIL] 停止播放进度定时器');
				clearInterval(this.progressTimer);
				this.progressTimer = null;
			}
		},
		
		// 重置播放进度
		resetPlayProgress() {
			console.log('[DETAIL] 重置播放进度');
			this.localPlayedDuration = 0;
			this.stopProgressTimer();
			this.updatePlayDetailInfo();
		},
		
		// 处理播放状态变化（根据设备返回的 playback_status）
		handlePlaybackStatusChange(playbackStatus, playedDuration) {
			console.log('[DETAIL] 处理播放状态变化:', playbackStatus, '已播放时长:', playedDuration);
			
			// 保存当前播放状态
			this.currentPlaybackStatus = playbackStatus;
			
			switch (playbackStatus) {
				case 'playing':
					// 播放状态：同步时间并启动定时器累加
					console.log('[DETAIL] 状态: playing - 启动定时器累加');
					this.localPlayedDuration = playedDuration || 0;
					this.paused = false;
					this.currentPattern.status = 1;
					// 确保定时器启动
					if (!this.progressTimer) {
						this.startProgressTimer();
					}
					break;
					
				case 'paused':
					// 暂停状态：同步时间但不累加
					console.log('[DETAIL] 状态: paused - 保持时间不累加');
					this.localPlayedDuration = playedDuration || 0;
					this.paused = true;
					this.currentPattern.status = 0;
					this.stopProgressTimer();
					break;
					
				case 'homing':
				case 'sweeping':
				case 'stopped':
					// 停止/归位/清扫状态：显示 0
					console.log('[DETAIL] 状态:', playbackStatus, '- 显示时间为 0');
					this.localPlayedDuration = 0;
					this.paused = true;
					this.currentPattern.status = 0;
					this.stopProgressTimer();
					break;
					
				default:
					// 未知状态：按停止处理
					console.warn('[DETAIL] 未知状态:', playbackStatus, '- 按停止处理');
					this.localPlayedDuration = 0;
					this.paused = true;
					this.currentPattern.status = 0;
					this.stopProgressTimer();
					break;
			}
			
			// 更新显示
			this.updatePlayDetailInfo();
		},
		
		// 添加时间格式化方法
		formatTime(seconds) {
			if (!seconds || seconds <= 0) return '00:00';

			const minutes = Math.floor(seconds / 60);
			const remainingSeconds = Math.floor(seconds % 60);

			// 确保分钟和秒数都显示两位数
			const formattedMinutes = minutes < 10 ? `0${minutes}` : minutes;
			const formattedSeconds = remainingSeconds < 10 ? `0${remainingSeconds}` : remainingSeconds;

			return `${formattedMinutes}:${formattedSeconds}`;
		},

		// 从MQTT缓存更新设备状态
		async updateFromMqttCache() {
			if (!this.deviceSn) return;
        
			const cachedStatus = deviceStore.getDeviceStatus(this.deviceSn);
			const isOnline = deviceStore.isDeviceOnline(this.deviceSn);
        
			// 更新设备在线状态
			if (this.deviceDetail) {
				this.deviceDetail.device_status = isOnline ? 1 : 0;
			}
        
			// 如果缓存中有播放信息，使用缓存数据
			if (cachedStatus && cachedStatus.device && cachedStatus.device.current_pattern) {
				const currentPatternFileName = cachedStatus.device.current_pattern;
				const playbackStatus = cachedStatus.device.playback_status || 'stopped';
            
				// 检查是否有文件名
				if (currentPatternFileName) {
					// 构建播放状态对象
					const patternStatus = {
						status: playbackStatus === 'playing' ? 1 : 0,
						elapsed_time: cachedStatus.device.played_duration || 0,
						progress: cachedStatus.playback?.progress || 0
					};
					
					await this.loadPatternByFileName(currentPatternFileName, patternStatus);
				} else {
					// 直接使用缓存数据，但只更新播放状态，保持显示数据不变
					this.currentPattern = {
						...this.currentPattern,
						// 只更新播放相关状态，保持显示数据不变
						status: playbackStatus === 'playing' ? 1 : 0,
						elapsed_time: cachedStatus.device.played_duration || this.currentPattern.elapsed_time,
						progress: cachedStatus.playback?.progress || this.currentPattern.progress
					};
				}
            
				this.updatePlayDetailInfo();
			}
			
			// 更新播放模式
			const playbackMode = deviceStore.getPlaybackMode(this.deviceSn);
			if (playbackMode) {
				this.playbackMode = playbackMode;
				console.log(`[DETAIL] 从缓存获取播放模式: ${playbackMode}`);
			}
		},

		// 设备状态变化回调
		async onDeviceStatusChange(deviceSn, status) {
			if (deviceSn !== this.deviceSn) {
				return;
			}
			
			console.log(`[DETAIL] 收到设备 ${deviceSn} 状态变化:`, status);
			
			// 防御性检查:如果status不存在(设备已删除),直接返回
			if (!status) {
				console.warn(`[DETAIL] 设备 ${deviceSn} 状态为空,可能已被删除`);
				return;
			}
			
			// 更新设备在线状态(来自心跳或device数据)
			if (status.heartbeat && status.heartbeat.online !== undefined) {
				if (this.deviceDetail) {
					this.deviceDetail.device_status = status.heartbeat.online ? 1 : 0;
				}
				console.log(`[DETAIL] 设备在线状态更新: ${status.heartbeat.online ? '在线' : '离线'}`);
			} else if (status.device && status.device.online !== undefined) {
				if (this.deviceDetail) {
					this.deviceDetail.device_status = status.device.online ? 1 : 0;
				}
				console.log(`[DETAIL] 设备在线状态更新: ${status.device.online ? '在线' : '离线'}`);
			}
			
			// 更新图案播放状态（来自device数据）
			if (status.device && status.device.current_pattern) {
				const currentPatternFileName = status.device.current_pattern;
				const playbackStatus = status.device.playback_status || 'stopped';
				const currentFileName = this.currentPattern.file_name;

				console.log(`[DETAIL] 图案状态更新: ${currentFileName} -> ${currentPatternFileName}, status: ${playbackStatus}`);
				
				// 检查是否有文件名信息
				if (currentPatternFileName) {
					// 如果文件名发生变化，需要重新加载图案详细信息
					if (currentPatternFileName !== currentFileName) {
						const patternStatus = {
							status: playbackStatus === 'playing' ? 1 : 0,
							elapsed_time: status.device.played_duration || 0,
							progress: status.playback?.progress || 0
						};
						
						console.log('[DETAIL] 检测到文件名变化，加载新图案:', currentPatternFileName, '播放状态:', playbackStatus);
						
						await this.loadPatternByFileName(currentPatternFileName, patternStatus);
						
						// 根据播放状态处理定时器和显示
						this.handlePlaybackStatusChange(playbackStatus, status.device.played_duration || 0);
						
					} else {
						// 文件名没变，只更新播放状态
						const newStatus = playbackStatus === 'playing' ? 1 : 0;
						const oldStatus = this.currentPattern.status;
						
						this.currentPattern = {
							...this.currentPattern,
							status: newStatus,
							elapsed_time: status.device.played_duration !== undefined ? status.device.played_duration : this.currentPattern.elapsed_time,
							progress: status.playback?.progress !== undefined ? status.playback.progress : this.currentPattern.progress
						};
						
						// 根据播放状态处理定时器和显示
						this.handlePlaybackStatusChange(playbackStatus, status.device.played_duration || 0);
					}
				}
				
				this.updatePlayDetailInfo();
			}
			
			// 更新其他业务状态
			if (status.lightSettings) {
				console.log(`[DETAIL] 灯光设置更新:`, status.lightSettings);
			}
			
			// 更新播放模式
			if (status.playback && status.playback.playback_mode) {
				this.playbackMode = status.playback.playback_mode;
				console.log(`[DETAIL] 播放模式更新: ${this.playbackMode}`);
			}
		},

		// 根据文件名加载图案详细信息
		async loadPatternByFileName(fileName, patternStatus) {
			try {
				console.log(`[DETAIL] 通过文件名加载图案详情: ${fileName}`, patternStatus);
				
				// 重置播放进度
				this.resetPlayProgress();
				
				const res = await patternApi.getPatternByFileName(fileName);
				
				if (res.errCode === 0 && res.data) {
					console.log('[DETAIL] 图案详情加载成功:', res.data);
					// 使用API数据作为显示信息，使用patternStatus的播放状态
					this.currentPattern = {
						pattern_id: res.data.pattern_id || res.data.id || '',
						pattern_name: res.data.name || res.data.pattern_name || fileName,
						preview_image: res.data.preview_image || res.data.image_url || '',
						description: res.data.description || '',
						file_name: fileName,
						// 使用传入的patternStatus更新播放状态
						status: patternStatus?.status !== undefined ? patternStatus.status : 0,
						duration:  res.data.duration || 0,
						elapsed_time: patternStatus?.elapsed_time !== undefined ? patternStatus.elapsed_time : 0,
						progress: patternStatus?.progress !== undefined ? patternStatus.progress : 0
					};
					
					// 同步本地播放进度
					this.localPlayedDuration = patternStatus?.elapsed_time || 0;
					
					// 如果是播放状态，启动定时器
					if (patternStatus?.status === 1) {
						this.startProgressTimer();
					}
				} else {
					// 使用文件名作为默认显示，使用patternStatus的播放状态
					this.currentPattern = {
						pattern_id: '',
						pattern_name: fileName.replace(/\.[^/.]+$/, ""), // 去掉扩展名作为默认名称
						preview_image: '',
						file_name: fileName,
						// 使用传入的patternStatus更新播放状态
						status: patternStatus?.status !== undefined ? patternStatus.status : 0,
						duration: 0, // 默认值为0，等待API返回
						elapsed_time: patternStatus?.elapsed_time !== undefined ? patternStatus.elapsed_time : 0,
						progress: patternStatus?.progress !== undefined ? patternStatus.progress : 0
					};
					
					// 同步本地播放进度
					this.localPlayedDuration = patternStatus?.elapsed_time || 0;
					
					// 如果是播放状态，启动定时器
					if (patternStatus?.status === 1) {
						this.startProgressTimer();
					}
				}
			} catch (error) {
				console.error('通过文件名加载图案详情失败:', error);
				// 出错时使用文件名作为默认显示，使用patternStatus的播放状态
				this.currentPattern = {
					pattern_id: '',
					pattern_name: fileName.replace(/\.[^/.]+$/, ""),
					preview_image: '',
					file_name: fileName,
					// 使用传入的patternStatus更新播放状态
					status: patternStatus?.status !== undefined ? patternStatus.status : 0,
					duration: 0, // 默认值为0，等待API返回
					elapsed_time: patternStatus?.elapsed_time !== undefined ? patternStatus.elapsed_time : 0,
					progress: patternStatus?.progress !== undefined ? patternStatus.progress : 0
				};
				
				// 同步本地播放进度
				this.localPlayedDuration = patternStatus?.elapsed_time || 0;
			}
		},

		// 更新播放详情信息
		updatePlayDetailInfo() {
			if (!this.currentPattern) return;
			
			// 优先使用本地播放进度，如果本地进度为0则从 deviceStore 获取
			let playedDuration = this.localPlayedDuration;
			if (playedDuration === 0) {
				const deviceStatus = deviceStore.getDeviceStatus(this.deviceSn);
				playedDuration = deviceStatus?.device?.played_duration || 0;
				// 同步本地进度
				this.localPlayedDuration = playedDuration;
			}
			
			// 使用格式化方法转换时间
			const formattedCurrent = this.formatTime(playedDuration);
			const formattedDuration = this.formatTime(this.currentPattern.duration || 0);

			this.playDetailInfo = {
				current: formattedCurrent,
				duration: formattedDuration,
				current_value: playedDuration,
				duration_value: this.currentPattern.duration || 100,
			};
			
			// 更新播放状态
			this.paused = this.currentPattern.status !== 1; // 1=播放中
		},

		lightControl() {
			this.isPopupOpen = true;
			this.$refs.ref_light_control.open(this.deviceSn)
		},
		playControl() {
			this.isPopupOpen = true;
			this.$refs.ref_play_control.open(this.deviceSn)
		},
		// 弹窗关闭回调
		onPopupClose() {
			this.isPopupOpen = false;
		},
		clickLeft() {
			uni.navigateBack()
		},
		clickRight() {
			uni.navigateTo({
				url: '/pages/device/device-setting?sn=' + this.deviceSn
			})
		},
		// 切换歌曲  --上一首或下一首
		async handleChangePlay(count) {
			// 检查是否禁用
			if (this.isControlDisabled) {
				uni.showToast({
					title: this.disabledReasonText,
					icon: 'none'
				});
				return;
			}
			
			console.log('切换图案, count:', count);
			if (!this.deviceSn) {
				uni.showToast({
					title: this.$t('detail.deviceInfoNotLoaded'),
					icon: 'error'
				});
				return;
			}			// 重置播放进度（切换歌曲时归零）
			console.log('[DETAIL] 切换歌曲，重置播放进度为 0');
			this.resetPlayProgress();

			try {
				if (count === 1) {
					// 下一个图案
					const result = await mqttApi.nextPattern(this.deviceSn);
					console.log('切换到下一个图案结果:', result);
					if (result) {
						uni.showToast({
							title: this.$t('detail.switchingToNext'),
							icon: 'success'
						});
					} else {
						uni.showToast({
							title: this.$t('detail.switchFailed'),
							icon: 'error'
						});
					}
				} else if (count === -1) {
					// 上一个图案
					const result = await mqttApi.prevPattern(this.deviceSn);
					console.log('切换到上一个图案结果:', result);
					if (result) {
						uni.showToast({
							title: this.$t('detail.switchingToPrev'),
							icon: 'success'
						});
					} else {
						uni.showToast({
							title: this.$t('detail.switchFailed'),
							icon: 'error'
						});
					}
				}
			} catch (error) {
				console.error('图案切换异常:', error);
				uni.showToast({
					title: this.$t('detail.switchFailed'),
					icon: 'error'
				});
			}
		},
		//拖动 完成
		handleChange(event) {
			// this.$audio.seek(event.target.value);
			let progress = event.target.value;

		},

		//播放或暂停
	async playMusic() {
		// 检查是否禁用
		if (this.isControlDisabled) {
			uni.showToast({
				title: this.disabledReasonText,
				icon: 'none'
			});
			return;
		}
		
		if (!this.deviceSn) {
			uni.showToast({
				title: this.$t('detail.deviceInfoNotLoaded'),
				icon: 'error'
			});
			return;
		}
		
		try {
			if (this.paused || this.currentPattern.status !== 1) {
				// 当前是暂停状态，开始绘图
				const result = await mqttApi.startDrawing(this.deviceSn);
				console.log('开始绘图结果:', result);
					
					if (result) {
						// 乐观更新UI状态
						this.paused = false;
						this.currentPattern.status = 1; // 设置为播放状态
						
						// 启动播放进度定时器（继续从当前进度开始）
						this.startProgressTimer();
						
						uni.showToast({
							title: this.$t('detail.startDrawing'),
							icon: 'success'
						});
					} else {
						uni.showToast({
							title: this.$t('detail.startDrawingFailed'),
							icon: 'error'
						});
					}
				} else {
					// 当前是播放状态，暂停绘图
					const result = await mqttApi.stopDrawing(this.deviceSn);
					console.log('暂停绘图结果:', result);
					
					if (result) {
						// 乐观更新UI状态
						this.paused = true;
						this.currentPattern.status = 0; // 设置为暂停状态
						
						// 停止播放进度定时器（但保持当前进度不清零）
						this.stopProgressTimer();
						
						console.log('[DETAIL] 暂停播放，保持当前进度:', this.localPlayedDuration);
						
						uni.showToast({
							title: this.$t('detail.pauseDrawing'),
							icon: 'success'
						});
					} else {
						uni.showToast({
							title: this.$t('detail.pauseDrawingFailed'),
							icon: 'error'
						});
					}
				}
			} catch (error) {
				console.error('播放控制异常:', error);
				uni.showToast({
					title: this.$t('detail.operationFailed'),
					icon: 'error'
				});
			}
		},
		playList() {
			if (this.deviceSn) {
				uni.navigateTo({
					url: '/pages/play-list/index?sn=' + this.deviceSn
				})
			}
		},
		
		// 切换播放模式
	async togglePlaybackMode() {
		// 检查是否禁用
		if (this.isControlDisabled) {
			uni.showToast({
				title: this.disabledReasonText,
				icon: 'none'
			});
			return;
		}
		
		if (!this.deviceSn) {
			uni.showToast({
				title: this.$t('detail.deviceInfoNotLoaded'),
				icon: 'error'
			});
			return;
		}			try {
				// 循环切换播放模式: sequential -> random -> single_loop -> sequential
				let newMode = 'sequential';
				switch (this.playbackMode) {
					case 'sequential':
						newMode = 'random';
						break;
					case 'random':
						newMode = 'single_loop';
						break;
					case 'single_loop':
						newMode = 'sequential';
						break;
					default:
						newMode = 'sequential';
				}

				console.log(`[DETAIL] 切换播放模式: ${this.playbackMode} -> ${newMode}`);

				// 发送MQTT命令
				const result = await mqttApi.setPlaybackMode(this.deviceSn, newMode);

				if (result) {
					// 乐观更新UI
					this.playbackMode = newMode;
					
					// 显示对应的提示
					let modeName = '';
					switch (newMode) {
						case 'sequential':
							modeName = this.$t('detail.sequentialMode');
							break;
						case 'random':
							modeName = this.$t('detail.randomMode');
							break;
						case 'single_loop':
							modeName = this.$t('detail.singleLoopMode');
							break;
					}
					
					uni.showToast({
						title: modeName,
						icon: 'success'
					});
				} else {
					uni.showToast({
						title: this.$t('detail.switchModeFailed'),
						icon: 'error'
					});
				}
			} catch (error) {
				console.error('切换播放模式异常:', error);
				uni.showToast({
					title: this.$t('detail.operationFailed'),
					icon: 'error'
				});
			}
		},
		
		// 获取播放状态文本
		getPlaybackStatusText() {
			switch (this.currentPlaybackStatus) {
				case 'playing':
					return '绘图中';
				case 'paused':
					return '已暂停';
				case 'homing':
					return '归零中';
				case 'sweeping':
					return '扫图中';
				case 'stopped':
					return '已停止';
				default:
					return '待机中';
			}
		}
	}
}
</script>
<style lang="scss" scoped>
.common-bg {
	overflow-x: hidden;
	
	// iOS弹窗打开时防止底层滚动穿透
	&.popup-open {
		position: fixed;
		width: 100%;
		height: 100%;
		overflow: hidden;
	}
}

// 顶部导航栏样式
.device-name-title {
	font-size: 32rpx;
	font-weight: 500;
	color: rgba(0, 0, 0, 0.85);
	line-height: 1.4;
	margin-bottom: 4rpx;
}

.device-status-info {
	font-size: 22rpx;
	color: rgba(0, 0, 0, 0.45);
	display: flex;
	align-items: center;
	justify-content: center;
	line-height: 1.2;
	
	.status-dot {
		margin-right: 4rpx;
		
		// 在线圆点 - 绿色（与首页一致）
		&.online {
			color: #22C55D;
		}
		
		// 离线圆点 - 灰色（与首页一致）
		&.offline {
			color: rgba(0, 0, 0, 0.4);
		}
	}
	
	.status-text {
		color: rgba(0, 0, 0, 0.45);
	}
	
	.status-divider {
		margin: 0 8rpx;
		color: rgba(0, 0, 0, 0.25);
		
		// 播放状态颜色应用到圆点
		&.playback-status {
			&.status-playing {
				color: #3C82F6; // 绘图中 - 蓝色
			}
			
			&.status-paused {
				color: #FFA500; // 已暂停 - 橙色
			}
			
			&.status-homing {
				color: #EB4839; // 归零中 - 红色
			}
			
			&.status-sweeping {
				color: #9333EA; // 扫图中 - 紫色
			}
			
			&.status-stopped {
				color: #FFFFFF; // 已停止 - 白色
			}
			
			// 待机中保持默认灰色
		}
	}
}

.bottom-control {
	width: 100%;
	max-width: 100%;
	margin: 40rpx auto 0;

	.progress {
		width: 100%;
		display: flex;
		align-items: center;

		.audio-slider {
			flex: 1;
			margin: 0;
		}
	}

	.audio-number {
		font-size: 24rpx;
		line-height: 1;
		color: rgba(0, 0, 0, 0.4);
	}

	.iconList {
		justify-content: center;
		align-items: center;
		margin-top: 26rpx;

		.iconfont {
			color: #fff;
			font-size: 48rpx;
		}
	}
}

.top-status {
	.dot {
		width: 12rpx;
		height: 12rpx;
		border-radius: 100%;
		margin-right: 8rpx;
		display: inline-block;
		background-color: #22C55D;

		&.no {
			background-color: rgba(0, 0, 0, 0.4);
		}
	}
}

.top-status {
	.dot {
		width: 12rpx;
		height: 12rpx;
		border-radius: 100%;
		margin-right: 8rpx;
		display: inline-block;
		background-color: #22C55D;

		&.no {
			background-color: rgba(0, 0, 0, 0.4);
		}
	}
}

.img-box {
	width: 670rpx;
	max-width: calc(100vw - 80rpx);
	height: 670rpx;
	margin: 40rpx auto 0;
	border-radius: 100%;
	position: relative;

	.img {
		width: 520rpx;
		height: 520rpx;
		border-radius: 100%;
		margin: 0 auto;
		animation: rotate 40s linear infinite; // 添加旋转动画
	}
}

.play-btn-box {
	width: 100%;
	max-width: 100%;
	margin-top: 48rpx;
	box-sizing: border-box;

	.play-img {
		width: 72rpx;
		height: 74rpx;
		transition: opacity 0.2s;
		
		&.disabled {
			opacity: 0.3;
			cursor: not-allowed;
		}
	}

	.play-img-btn {
		width: 108rpx;
		height: 110rpx;
		margin: 0 100rpx;
		transition: opacity 0.2s;
		
		&.disabled {
			opacity: 0.3;
			cursor: not-allowed;
		}
	}
}

.btns-box {
	width: 100%;
	max-width: 100%;
	margin-top: 60rpx;
	padding: 0 40rpx;
	box-sizing: border-box;
	display: flex;
	align-items: center;
	justify-content: space-between;

	.control-img {
		width: 40rpx;
		height: 40rpx;
		opacity: 0.5;
		transition: opacity 0.2s;
		
		&.disabled {
			opacity: 0.3;
			cursor: not-allowed;
		}
	}
}

@keyframes rotate {
	from {
		transform: rotate(0deg);
	}

	to {
		transform: rotate(360deg);
	}
}
</style>